﻿using System;
using System.Net;
using System.IO;
using System.Xml;
using System.Text;

/*
 * According to Ericsson's API
 */
class EricssonAPI
{
    private static String myKey = "cowJnNWznEbEfOTHCtcUi7FBO1hHTuUPWr9ajrz3";

    /*
     * Use CID, LAC, MCC and MNC
     */ 
    public static bool GetLatLng(int CID, int LAC, int MCC, int MNC,
                                 out double lat, out double lng)
    {
        String url = "http://cellid.labs.ericsson.net/xml/lookup?key="+myKey+"&base=10";
        url += "&cellid="+CID;
        url += "&lac="+LAC;
        url += "&mcc="+MCC;
        url += "&mnc="+MNC;

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(
                new Uri(url));
        req.Method = "GET";

        //Get response
        HttpWebResponse res = (HttpWebResponse)req.GetResponse();
        byte[] tmpBytes = new byte[res.ContentLength];
        int totalBytesRead = 0;
        while (totalBytesRead < tmpBytes.Length)
        {
            totalBytesRead += res.GetResponseStream().Read(
                tmpBytes, totalBytesRead, tmpBytes.Length - totalBytesRead);
        }

        //Check state and parse XML
        if (res.StatusCode == HttpStatusCode.OK)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml( Encoding.UTF8.GetString(tmpBytes) );
            
            XmlNode latNode = doc.GetElementsByTagName("latitude").Item(0);
            XmlNode lngNode = doc.GetElementsByTagName("longitude").Item(0);

            lat = Convert.ToDouble(latNode.FirstChild.Value);
            lng = Convert.ToDouble(lngNode.FirstChild.Value);

            return true;
        }

        lat = 0;
        lng = 0;
        return false;
    }
}